console.log('background is running')

let baseUrl = 'https://admin.buerluoji.cn'
let token = ''

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'simulateTyping',
    title: '布尔-模拟输入',
    contexts: ['editable'],
  })

  chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true })
})

chrome.contextMenus.onClicked.addListener(function (info) {
  if (info.menuItemId === 'simulateTyping') {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { action: 'simulateTyping' })
    })
  }
})

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('sender: ', sender)
  if (request.action === 'COUNT') {
    console.log('background has received a message from popup, and count is ', request?.count)
  }

  //side 发来的消息
  if (request.action === 'simulateTyping') {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.tabs.sendMessage(tabs[0].id, {
        action: 'simulateTyping',
        data: request.data,
        from: 'silder',
      })
    })
    return true
  }

   //side 发来的消息
   if (request.action === 'captureScreenshot') {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {

         // 执行截图操作
        chrome.tabs.captureVisibleTab(null, { format: 'jpeg', quality: 50 }, (dataUrl) => {
          console.log('dataUrl: ', dataUrl);
          if (dataUrl) {
            // 保存截图到本地存储
            saveScreenshotToLocalStorage(dataUrl);
            sendResponse(dataUrl)
          }
        });

      // chrome.tabs.sendMessage(tabs[0].id, {
      //   action: 'simulateTyping',
      //   data: request.data,
      //   from: 'silder',
      // })
    })
    return true
  }

  if (request.action === 'TOGGLESIDEPANEL') {
    chrome.sidePanel.open({ tabId: sender.tab.id })
    return true
  }

  if (request.action === 'GETACCOUNT') {
    fetch(`${baseUrl}/bool-admin/wechat/publicaccount/list_account`, {
      method: 'GET',
      headers: {
        token,
      },
    })
      .then((response) => response.json())
      .then((data) => {
        sendResponse(data)
      })
      .catch((error) => console.error('Error:', error))

    return true
  }


  if (request.action === 'GENARTICLE') {
    fetch(`${baseUrl}/bool-admin/wechat/publicarticles/gen_article`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        token,
      },
      body: JSON.stringify(request.data),
    })
      .then((response) => response.json())
      .then((data) => {
        sendResponse(data)
      })
      .catch((error) => console.error('Error:', error))
    return true
  }

  if (request.action === 'SETBASEURL') {
    baseUrl = request.data
    return true
  }

  if (request.action === 'SETTOKEN') {
    token = request.data
    return true
  }
})

function saveScreenshotToLocalStorage(dataUrl) {
  // 获取当前时间戳，作为图片唯一标识
  const timestamp = new Date().toISOString();
  const key = `sc_${timestamp}`;

  // 将截图存储到 localStorage
  chrome.storage.local.get('screenshots', (result) => {
    let screenshots = result.screenshots || [];
    screenshots.push({ key, dataUrl });

    // 保存更新后的截图数组
    chrome.storage.local.set({ screenshots }, () => {
      console.log('Screenshot saved:', key);
    });
  });
}
